package com.pat.miniloyalty;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import javax.jdo.Extent;
import javax.jdo.FetchPlan;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tools.ant.taskdefs.Sync.MyCopy;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class TranListServlet extends HttpServlet
{

	/**
	 * List purchase for logged in company
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		// Check if company is logged in
		User company = UserServiceFactory.getUserService().getCurrentUser();
		if( company == null )
		{
			resp.sendRedirect(UserServiceFactory.getUserService().createLoginURL(req.getRequestURI()));
		}
		
		PersistenceManager pm = LoyaltyPmf.get().getPersistenceManager();
		Query query = pm.newQuery(TranData.class);
		// contains result of query or null
		List<TranData> results = null;
		
		// What type of statistic - by user, by period, etc...
		String type = req.getParameter("type") == null ? "" + MyConstants.UNKNOWN_ID : req.getParameter("type");
		final int statType = Integer.parseInt(type);

		Logist.log("TranList", "Displaying statistics...");

		switch( statType )
		{
			case MyConstants.STAT_BY_USER:
				final String uid = req.getParameter("uid");
				if( uid != null )
				{
					query.setFilter("uid == uidParam");
					query.setOrdering("createdAt desc");
					query.declareParameters("String uidParam");
					results = (List<TranData>) query.execute(uid);
					Logist.log("TranList", query.toString());
				}else
				{
					Logist.log("TranList", "No client ID to list transactions!");
				}
				break;
			default:
				Logist.log("TranList", "Bad statistics parameters!");
				break;
		}
		
		resp.setContentType("text/html");
		if( results != null )
		{
			StringBuilder sb = new StringBuilder(100 * results.size());
			sb.append("<div class='tran_list_header>Total:" + results.size() + "</div>'");
			for( TranData td : results )
			{
				Logist.log("TranList", "Purchase at: " + td.getCreatedAt());
				sb.append("<div class='tran_list_key'>" + td.getKey().toString() + "</div>");
				sb.append("<div class='tran_list_sum'>" + td.getSumInMinorCurrency() + "</div>");
				sb.append("<div class='tran_list_date'>" + td.getCreatedAt() + "</div>");
			}
			resp.getWriter().write(sb.toString());
		}else
		{
			Logist.log("TranList", "No statistics for purchase!");
			resp.getWriter().write("No data for your request!");
		}
	}
	
}
